<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加商品卡片 -->

    <el-card class="box-card">
      <!-- 添加商品新页面 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <!-- <el-step title="商品内容"></el-step> -->
        <el-step title="完成"></el-step>
      </el-steps>

      <template>
        <el-form label-position="top" label-width="80px" :model="addShopForm">
          <el-tabs
            tab-position="left"
            v-model="active"
            :before-leave="beforeLeave"
            @tab-click="handleClick"
          >
            <el-tab-pane label="基本信息" name="0">
              <div class="info">
                <el-form-item label="商品名称">
                  <el-input v-model="addShopForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="价格">
                  <el-input
                    type="number"
                    v-model="addShopForm.goods_price"
                  ></el-input>
                </el-form-item>
                <el-form-item label="数量">
                  <el-input
                    type="number"
                    v-model="addShopForm.goods_number"
                  ></el-input>
                </el-form-item>
                <el-form-item label="重量">
                  <el-input
                    type="number"
                    v-model="addShopForm.goods_weight"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品介绍">
                  <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入内容"
                    v-model="addShopForm.goods_introduce"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                  <el-cascader
                    v-model="CateValue"
                    :options="CateList"
                    :props="{
                      expandTrigger: 'hover',
                      label: 'cat_name',
                      value: 'cat_id',
                    }"
                    @change="handleChange"
                  ></el-cascader>
                </el-form-item>
              </div>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in manyData"
                :key="index"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    v-for="(item1, index1) in item.attr_vals"
                    :key="index1"
                    :label="item1"
                    >{{ item1 }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in onlyData"
                :key="index"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                list-type="picture-card"
                :headers="hearderConfig"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleImg"
              >
                <i class="el-icon-plus"></i>
              </el-upload>

              <el-button type="primary" round @click="submitShop"
                >提交</el-button
              >
              <!-- 提示框 -->
              <el-dialog
                title="图片预览"
                :visible.sync="imgdialogVisible"
                width="30%"
              >
                <img :src="CurrentImg" alt="" class="imgClass" />
              </el-dialog>
            </el-tab-pane>
            <!-- <el-tab-pane label="商品内容" name="4">商品内容</el-tab-pane> -->
          </el-tabs>
        </el-form>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: 0, //当前步骤条状态
      CateValue: [],
      hearderConfig: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      CateList: [],
      addShopForm: {
        // id: "",
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_introduce: "",
        goods_cat: "",
        pics: [],
        attrs: "",
      },
      imgdialogVisible: false,
      manyData: [],
      onlyData: [],
      CurrentImg: "",
    };
  },
  mounted() {
    this.getshopCateList();
  },
  methods: {
    //   改变级联选择框触发
    handleChange() {},

    // 获取商品分类列表数据
    async getshopCateList() {
      const { data: res } = await this.$axios.get("categories");
      console.log(res);
      this.CateList = res.data;
    },

    // 切换标签页之前
    beforeLeave(active, old) {
      console.log("要去的页面:" + active, "老页面:" + old);
      if (active != 0 && this.CateValue.length == 0) {
        this.$message.success("请先选择商品分类");
        return false;
      }
    },

    // 点击标签页
    async handleClick() {
      console.log(this.active);
      if (this.active == 1) {
        const { data: res } = await this.$axios.get(
          "categories/" + this.CateValue[2] + "/attributes",
          { params: { sel: "many" } }
        );
        this.manyData = res.data;
        this.manyData.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
        });
        // console.log(this.manyData,"数据");
      } else if (this.active == 2) {
        const { data: res } = await this.$axios.get(
          "categories/" + this.CateValue[2] + "/attributes",
          { params: { sel: "only" } }
        );
        this.onlyData = res.data;
        console.log(this.onlyData);
        // this.manyData.forEach(item => {
        //   item.attr_vals = item.attr_vals.split(',')
        // });
      }
    },

    // 点击预览图片
    handlePictureCardPreview(file) {
      this.imgdialogVisible = true;
      this.CurrentImg = file.response.data.url;
      // console.log(file);
    },

    // 点击移除图片
    handleRemove(file, fileList) {
      const index = this.addShopForm.pics.findIndex(function(item) {
        //  console.log(item.pic,"本地");
        //  console.log(file.response.data.tmp_path,"当前数据");
        return item.pic == file.response.data.tmp_path;
      });
      this.addShopForm.pics.splice(index, 1);
      console.log(this.addShopForm.pics);
    },

    // 图片请求成功函数
    handleImg(res) {
      var pic = {
        pic: res.data.tmp_path,
      };
      this.addShopForm.pics.push(pic);
      console.log("图片数据请求成功");
    },

    // 点击提交上传商品信息
    async submitShop() {
      const flag = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (flag == "confirm") {
        this.addShopForm.goods_cat = this.CateValue.join(",");
        // this.addShopForm.attrs =
        console.log(this.addShopForm);
        this.attrs = [
          ...this.onlyData.map((item) => {
            return {
              attr_id: item.attr_id,
              attr_value:item.attr_vals,
            };
          }),
          ...this.manyData.map(item=>{
          return {
              attr_id: item.attr_id,
              attr_value:item.attr_vals.join(','),
            };
        })
        ]
        const {data:res} = await this.$axios.post('goods',{
          ...this.addShopForm
        })
        if(res.meta.status == 201){
          this.$router.push('/home/goods')
          this.getshopCateList()
          this.$message.success("添加商品成功")
        }
      } else {
        this.$message.error("添加商品失败");
      }
    },
  },
};
</script>

<style>
.el-steps {
  margin-top: 20px;
}
.el-step__title {
  font-size: 14px;
}
.el-tabs {
  margin-top: 20px;
}

.el-tabs__content {
  width: 600px;
  padding-left: 100px;
}

.imgClass {
  width: 100%;
}
</style>
